import React from "react";
import { Routes, Route, Outlet, Link, useLocation } from "react-router-dom";
import { AppOutline, BillOutline, ShopbagOutline, UserOutline } from 'antd-mobile-icons'
import './App.less';

const Home = React.lazy(() => import("./modules/home"));
const Orders = React.lazy(() => import("./modules/orders"));
const GoodsCenter = React.lazy(() => import("./modules/goods"));
const Mine = React.lazy(() => import("./modules/mine"));
const NoMatch = React.lazy(() => import("./modules/misc/NoMatch"));
const ShopList = React.lazy(() => import('./modules/shop/list'));
const AddShop = React.lazy(() => import('./modules/shop/add'));
const DistributeRecords = React.lazy(() => import('./modules/records/distribute'));
const SnapList = React.lazy(() => import('./modules/records/snap'));

function TabBar() {
  const location = useLocation();
  const pathname = location.pathname;

  const items = [
    { to: "/", label: "首页", icon: AppOutline },
    { to: "/orders", label: "订单管理", icon: BillOutline },
    { to: "/goods", label: "货源中心", icon: ShopbagOutline },
    { to: "/mine", label: "我的", icon: UserOutline },
  ];

  return (
    <div className="tabbar">
      {items.map((item) => {
        const isActive = pathname === item.to || (item.to !== '/' && pathname.startsWith(item.to) && pathname === item.to);
        const Icon = item.icon;
        return (
          <Link key={item.to} to={item.to} className={`tabbar-item ${isActive ? 'active' : ''}`}>
            <Icon fontSize={22} />
            <span className="label">{item.label}</span>
          </Link>
        );
      })}
    </div>
  );
}

function Layout() {
  const location = useLocation();
  const pathname = location.pathname;
  const showTab = pathname === '/' || pathname === '/orders' || pathname === '/goods' || pathname === '/mine';

  return (
    <div className="lapp-container">
      {showTab && <div className="tabbar-spacer" />}
      <Outlet />
      {showTab && <TabBar />}
    </div>
  );
}

export default function App() {
  return (
    <div className="lapp-container">
      <React.Suspense fallback={<>...</>}>
        <Routes>
          <Route path="/" element={<Layout />}>
            <Route index element={<Home />} />
            <Route path="orders" element={<Orders />} />
            <Route path="goods" element={<GoodsCenter />} />
            <Route path="mine" element={<Mine />} />
            <Route path="shops" element={<ShopList />} />
            <Route path="shops/add" element={<AddShop />} />
            <Route path="records/distribute" element={<DistributeRecords />} />
            <Route path="records/snap" element={<SnapList />} />
            <Route path="*" element={<NoMatch />} />
          </Route>
        </Routes>
      </React.Suspense>
    </div>
  );
}